import { Button, List, Avatar, message, Image } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import { request } from '../../utils/request.ts';
import { getUserData } from '../../utils/const.ts';
import Edit from './edit.jsx';
import './index.css';
import RemoteSelect from '../../components/RemoteSelect/index.jsx';
import ChangeCoach from './changeCoach.jsx'

const CoachCertificate = () => {
  const actionRef = useRef();
  const [coachChangeOpen, setCoachChangeOpen] = useState(false);
  const [record, setRecord] = useState({});
  const [open, setOpen] = useState(false);
  const [list, setList] = useState([]);
  const [initLoading, setInitLoading] = useState(true);
  const [pageNum, setPageNum] = useState(1);
  const [total, setTotal] = useState(0);
  const [userId, setUserId] = useState(-1);
  const [level, setLevel] = useState(() => {
    try {
      const userStr = getUserData();
      if (userStr) {
        const user = JSON.parse(userStr);
        return user.level;
      }
    } catch (e) { }
    return undefined;
  });
  const [cardId, setCardId] = useState();
  const pageSize = 20;
  const fetchList = async (nextPageNum = 1, append = false, searchUserId = userId, searchCardId = cardId) => {
    setInitLoading(true);
    const data = {
      pageNum: nextPageNum,
      pageSize,
      cardId: searchCardId || -1,
      userId: searchUserId || -1,
    };
    const res = await request('/api/coach/pageList', {
      method: 'POST',
      data,
    });
    setInitLoading(false);
    if (res?.data) {
      setTotal(res?.data?.total || 0);
      if (append) {
        setList(prev => [...prev, ...(res?.data?.records || [])]);
      } else {
        setList(res?.data?.records);
      }
    } else {
      message.error(res?.msg);
    }
  };
  useEffect(() => {
    fetchList(1, false, userId, cardId);
  }, [userId]);
  const handleLoadMore = () => {
    const nextPage = pageNum + 1;
    setPageNum(nextPage);
    fetchList(nextPage, true, userId, cardId);
  };
  const handleSearch = () => {
    setPageNum(1);
    fetchList(1, false, userId, cardId);
  };
  return (
    <>
      <div className='search'>
        {level === 1 ? (
          <RemoteSelect
            name="userId"
            label="教练"
            fetchUrl="/api/user/coach"
            fetchMethod="POST"
            fetchParams={{ status: '-1' }}
            mapOption={item => ({ label: item.name, value: item.id })}
            placeholder="请选择教练"
            // fieldProps={{
            //   value: userId,
            //   onChange: setUserId,
            //   allowClear: true,
            // }}
          />
        ) : null}
        <RemoteSelect
          name="cardId"
          label="教练证书"
          fetchUrl="/api/card/pageList"
          fetchMethod="POST"
          fetchParams={{ type: '1' }}
          mapOption={item => ({ label: item.name, value: item.id })}
          placeholder="请选择教练证书"
          fieldProps={{
            value: cardId,
            onChange: setCardId,
            allowClear: true,
          }}
        />
        <Button type="primary" onClick={handleSearch}>查询</Button>
      </div>
      <div className='toolbtns'>
        <Button type="primary" onClick={() => { setOpen(true); }}>新增</Button>
      </div>
      <List
        className="coach-certificate-list"
        loading={initLoading}
        itemLayout="horizontal"
        loadMore={
          list.length < total && (
            <Button onClick={handleLoadMore} loading={initLoading} style={{ width: '100%' } }>
              加载更多
            </Button>
          )
        }
        dataSource={list}
        renderItem={(item) => (
          <List.Item
            actions={[<Image src={item?.coachPic} width={200} />]}
          >
            <List.Item.Meta
              avatar={
                <>
                  <Avatar src={item?.pic} />
                  {/* <div>
                    <Button>调整头像</Button>
                  </div> */}
                </>
              }
            />
            <ul className='content'>
              <li>姓名：{item.name}</li>
              <li>生日/性别：{item.birthday}({ item.sex})</li>
              <li>单位信息：{item.address}</li>
              <li>手机/邮箱：{item.mobilephone}<span className='email'>{item.email}</span></li>
              <Button style={{marginTop:'8px'}} onClick={() => { setRecord(item); setCoachChangeOpen(true); }}  >变更会员信息</Button>
            </ul>
          </List.Item>
        )}
      />
      <Edit open={open} setOpen={setOpen} actionRef={actionRef} />
      <ChangeCoach open={coachChangeOpen} setOpen={setCoachChangeOpen} record={record} reload={() => { fetchList(1, false, userId, cardId) } } />
    </>
  );
};

export default CoachCertificate;
